import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  createBookshelf,
  getUserBookshelves,
  updateBookshelf,
  deleteBookshelf,
  moveFavoritesToBookshelf,
  getUserFavorites,
  type Bookshelf,
  type CreateBookshelfRequest,
  type UpdateBookshelfRequest,
  type BookshelfParams,
  type MoveFavoritesRequest,
  type UserFavoriteExtended,
  type FavoriteParamsExtended,
} from '@/api/novel'

export const useBookshelfStore = defineStore(
  'bookshelf',
  () => {
    // ==================== 状态定义 ====================

    // 书架列表
    const bookshelves = ref<Bookshelf[]>([])
    const bookshelvesLoading = ref(false)
    const bookshelvesError = ref<string | null>(null)

    // 当前选中的书架
    const currentBookshelfId = ref<number | null>(null)

    // 收藏列表
    const favorites = ref<UserFavoriteExtended[]>([])
    const favoritesLoading = ref(false)
    const favoritesError = ref<string | null>(null)

    // 分页状态
    const bookshelvesPage = ref(1)
    const bookshelvesHasMore = ref(true)
    const favoritesPage = ref(1)
    const favoritesHasMore = ref(true)

    // 操作状态
    const createLoading = ref(false)
    const updateLoading = ref(false)
    const deleteLoading = ref(false)
    const moveLoading = ref(false)

    // ==================== 计算属性 ====================

    // 当前选中的书架
    const currentBookshelf = computed(() => {
      if (!currentBookshelfId.value) return null
      return bookshelves.value.find(b => b.id === currentBookshelfId.value) || null
    })

    // 默认书架
    const defaultBookshelf = computed(() => {
      return bookshelves.value.find(b => b.isDefault) || null
    })

    // 非默认书架列表
    const customBookshelves = computed(() => {
      return bookshelves.value.filter(b => !b.isDefault)
    })

    // 当前书架的收藏数量
    const currentBookshelfCount = computed(() => {
      const bookshelf = currentBookshelf.value
      return bookshelf?.bookCount || 0
    })

    // 书架选项（用于下拉选择）
    const bookshelfOptions = computed(() => {
      return bookshelves.value.map(bookshelf => ({
        label: bookshelf.name,
        value: bookshelf.id,
        isDefault: bookshelf.isDefault,
        bookCount: bookshelf.bookCount || 0,
      }))
    })

    // ==================== API 调用方法 ====================

    /**
     * 获取用户书架列表
     */
    const fetchBookshelves = async (params: BookshelfParams = {}, reset = false) => {
      try {
        bookshelvesLoading.value = true
        bookshelvesError.value = null

        const response = await getUserBookshelves({
          page: reset ? 1 : bookshelvesPage.value,
          limit: 50,
          sortBy: 'sortOrder',
          sortOrder: 'asc',
          ...params,
        })

        if (reset || params.page === 1) {
          bookshelves.value = response.items
        } else {
          bookshelves.value.push(...response.items)
        }

        bookshelvesPage.value = response.meta.page
        bookshelvesHasMore.value = response.meta.hasNext

        // 如果没有选中书架，默认选中第一个
        if (!currentBookshelfId.value && bookshelves.value.length > 0) {
          currentBookshelfId.value = bookshelves.value[0].id
        }

        return response
      }
      catch (error: any) {
        bookshelvesError.value = error.message || '获取书架列表失败'
        throw error
      }
      finally {
        bookshelvesLoading.value = false
      }
    }

    /**
     * 创建书架
     */
    const createBookshelfAction = async (data: CreateBookshelfRequest) => {
      try {
        createLoading.value = true

        console.log('=== Store创建书架调试信息 ===')
        console.log('发送给API的数据:', data)

        const newBookshelf = await createBookshelf(data)
        bookshelves.value.push(newBookshelf)

        // 按排序重新排列
        bookshelves.value.sort((a, b) => a.sortOrder - b.sortOrder)

        uni.showToast({
          title: '书架创建成功',
          icon: 'success',
        })

        return newBookshelf
      }
      catch (error: any) {
        uni.showToast({
          title: error.message || '创建书架失败',
          icon: 'none',
        })
        throw error
      }
      finally {
        createLoading.value = false
      }
    }

    /**
     * 更新书架
     */
    const updateBookshelfAction = async (bookshelfId: number, data: UpdateBookshelfRequest) => {
      try {
        updateLoading.value = true

        const updatedBookshelf = await updateBookshelf(bookshelfId, data)

        // 更新本地状态
        const index = bookshelves.value.findIndex(b => b.id === bookshelfId)
        if (index !== -1) {
          bookshelves.value[index] = { ...bookshelves.value[index], ...updatedBookshelf }
        }

        uni.showToast({
          title: '书架更新成功',
          icon: 'success',
        })

        return updatedBookshelf
      }
      catch (error: any) {
        uni.showToast({
          title: error.message || '更新书架失败',
          icon: 'none',
        })
        throw error
      }
      finally {
        updateLoading.value = false
      }
    }

    /**
     * 删除书架
     */
    const deleteBookshelfAction = async (bookshelfId: number) => {
      try {
        deleteLoading.value = true

        await deleteBookshelf(bookshelfId)

        // 从本地状态中移除
        const index = bookshelves.value.findIndex(b => b.id === bookshelfId)
        if (index !== -1) {
          bookshelves.value.splice(index, 1)
        }

        // 如果删除的是当前选中的书架，切换到默认书架
        if (currentBookshelfId.value === bookshelfId) {
          currentBookshelfId.value = defaultBookshelf.value?.id || null
        }

        uni.showToast({
          title: '书架删除成功',
          icon: 'success',
        })
      }
      catch (error: any) {
        uni.showToast({
          title: error.message || '删除书架失败',
          icon: 'none',
        })
        throw error
      }
      finally {
        deleteLoading.value = false
      }
    }

    /**
     * 获取收藏列表
     */
    const fetchFavorites = async (params: FavoriteParamsExtended = {}, reset = false) => {
      try {
        favoritesLoading.value = true
        favoritesError.value = null

        const response = await getUserFavorites({
          page: reset ? 1 : favoritesPage.value,
          limit: 20,
          sortBy: 'createdAt',
          sortOrder: 'desc',
          ...params,
        })

        if (reset || params.page === 1) {
          favorites.value = response.items
        } else {
          favorites.value.push(...response.items)
        }

        favoritesPage.value = response.meta.page
        favoritesHasMore.value = response.meta.hasNext

        return response
      }
      catch (error: any) {
        favoritesError.value = error.message || '获取收藏列表失败'
        throw error
      }
      finally {
        favoritesLoading.value = false
      }
    }

    /**
     * 批量移动收藏到书架
     */
    const moveFavoritesAction = async (data: MoveFavoritesRequest) => {
      try {
        moveLoading.value = true

        const result = await moveFavoritesToBookshelf(data)

        // 更新本地收藏状态
        favorites.value.forEach(favorite => {
          if (data.novelIds.includes(favorite.novelId)) {
            favorite.bookshelfId = data.bookshelfId
          }
        })

        // 更新书架的书籍数量
        bookshelves.value.forEach(bookshelf => {
          if (bookshelf.id === data.bookshelfId && bookshelf.bookCount !== undefined) {
            bookshelf.bookCount += result.success
          }
        })

        uni.showToast({
          title: `成功移动 ${result.success} 本小说`,
          icon: 'success',
        })

        return result
      }
      catch (error: any) {
        uni.showToast({
          title: error.message || '移动失败',
          icon: 'none',
        })
        throw error
      }
      finally {
        moveLoading.value = false
      }
    }

    /**
     * 切换当前选中的书架
     */
    const selectBookshelf = (bookshelfId: number | null) => {
      currentBookshelfId.value = bookshelfId
    }

    /**
     * 重置状态
     */
    const reset = () => {
      bookshelves.value = []
      favorites.value = []
      currentBookshelfId.value = null
      bookshelvesPage.value = 1
      favoritesPage.value = 1
      bookshelvesHasMore.value = true
      favoritesHasMore.value = true

      // 重置错误状态
      bookshelvesError.value = null
      favoritesError.value = null

      // 重置加载状态
      bookshelvesLoading.value = false
      favoritesLoading.value = false
      createLoading.value = false
      updateLoading.value = false
      deleteLoading.value = false
      moveLoading.value = false
    }

    // ==================== 返回 ====================

    return {
      // 状态
      bookshelves,
      favorites,
      currentBookshelfId,
      bookshelvesLoading,
      favoritesLoading,
      bookshelvesError,
      favoritesError,
      createLoading,
      updateLoading,
      deleteLoading,
      moveLoading,

      // 计算属性
      currentBookshelf,
      defaultBookshelf,
      customBookshelves,
      currentBookshelfCount,
      bookshelfOptions,

      // 方法
      fetchBookshelves,
      createBookshelfAction,
      updateBookshelfAction,
      deleteBookshelfAction,
      fetchFavorites,
      moveFavoritesAction,
      selectBookshelf,
      reset,
    }
  },
  {
    persist: {
      key: 'bookshelf-store',
      storage: {
        getItem: uni.getStorageSync,
        setItem: uni.setStorageSync,
      },
      paths: [
        'bookshelves',
        'currentBookshelfId',
      ],
    },
  },
)